<template>
  <t-dialog
    :header="`${header}-${isEdit ? '修改经费' : '添加经费'}`"
    :visible.sync="visible"
    :onClose="closeDialog"
    :closeOnOverlayClick="false"
    confirmBtn="确定"
    :onConfirm="onSubmit"
    width="80%"
    top="5%"
  >
    <div id="main">
      <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium"> </t-loading>
      <div>
        <!-- 基本信息 -->
        <t-form ref="form" :data="formData" :rules="rules" labelWidth="180px">
          <t-row style="align-items: stretch; width: 99%" :gutter="14">
            <t-col :span="12">
              <t-card class="step-card" size="small" title="基本信息">
                <t-row style="align-items: stretch" :gutter="14">
                  <t-col :span="6">
                    <t-form-item label="投入时间：" name="year">
                      <t-date-picker style="width: 390px" v-model="formData.year"></t-date-picker>
                    </t-form-item>
                    <t-form-item label="自筹投入（万元）：" name="zcBudget">
                      <t-input-number style="width: 390px" clearable v-model="formData.zcBudget"></t-input-number>
                    </t-form-item>
                  </t-col>
                  <t-col :span="6">
                    <t-form-item label="上级拨款（万元）：" name="tbBudget">
                      <t-input-number style="width: 390px" clearable v-model="formData.tbBudget"></t-input-number>
                    </t-form-item>
                    <t-form-item label="备注：" name="note">
                      <t-input style="width: 390px" clearable v-model="formData.note"></t-input>
                    </t-form-item>
                  </t-col>
                </t-row>
              </t-card>
            </t-col>
          </t-row>
        </t-form>
      </div>
    </div>
  </t-dialog>
</template>

<script>
import { getDictList } from '@/api/system/dict/data';
import { getFiles } from '@/api/common';
import TinyMceEditor from '@/components/TinyMceEditor/index.vue';

import FileUpload from '@/components/FileUpload/index.vue';
import { TODAY } from '@/utils/date';
import dayjs from 'dayjs';

export default {
  name: 'draft-review',
  components: {
    TinyMceEditor,
    FileUpload,
  },
  dicts: ['formulate_type', 'standard_category', 'standard_property'],
  props: {
    header: String,
    objId: [String, Number],
    row: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      subBtnLoading: false,
      reviseNumDisable: true,
      visible: true,
      active: 1,
      subType: 2,
      projectFileData: [
        {
          id: 1,
          c1: '立项公文（盖章原件）',
          c2: '是',
          moduleKey: 'projectLXGW',
          fileIds: [],
          fileLists: [],
        },
        {
          id: 2,
          c1: '标准草案',
          c2: '是',
          fileIds: [],
          fileLists: [],
          moduleKey: 'projectBZCA',
        },
      ],
      projectFileColumns: [
        {
          colKey: 'id',
          title: '序号',
          align: 'center',
          width: 64,
        },
        {
          colKey: 'c1',
          title: '附件名称',
          align: 'center',
        },

        {
          colKey: 'c2',
          title: '是否必需',
          align: 'center',
        },
        {
          colKey: 'op',
          title: '操作',
          align: 'left',
        },
      ],
      deptMenuOptions: [],
      applyLoading: false,
      maxlength: 1000,
      lengthLimitObj: {
        description: 0,
      },
      tinymceFlag: 1,
      isEdit: false,
      dayjs,
      formData: {
        id: Date.parse(new Date()),
        platformId: this.objId,
        year: '',
        zcBudget: '',
        tbBudget: '',
        note: '',
      },
      rules: {
        year: [
          {
            required: true,
            message: '投入时间不能为空',
          },
        ],
        zcBudget: [
          {
            required: true,
            message: '自筹投入（万元）不能为空',
          },
        ],
        tbBudget: [
          {
            required: true,
            message: '上级拨款（万元）不能为空',
          },
        ],
      },
    };
  },
  async created() {
    await this.getDeptTreeSelect(this.$store.state.user.deptId);
    this.isEdit = !!this.row.id
    Object.assign(this.formData, this.row)
    // 判断路由有没有id传过来
    // 有id则是修改需要回显数据，无id则是新增
  },
  methods: {
    getDeptTreeSelect() {
      return this.$api.system.dept
        .treeSelectAllIn()
        .then((response) => {
          this.deptMenuOptions = response.data;
        })
        .catch((e) => {
          this.$message.error(e.toString());
        });
    },
    filterByTree(val, tree, children = 'children', id = 'id', label = 'label') {
      let text = '';
      const convert = (arr) => {
        arr.filter((item) => {
          if (item[id] === val) {
            text = item[label];
          } else if (item[children]) {
            return convert(item[children]);
          }
          return false;
        });
      };
      convert(tree);
      return text;
    },
    onSubmit() {
      this.$refs.form.validate().then(async (validateResult) => {
        if (validateResult === true) {
          // 路由有id修改，没有新增
          if (this.isEdit) {
            const message = '修改成功';
            this.subBtnLoading = true;
            this.$api.tjpt.budget
              .edit(this.formData)
              .then((response) => {
                this.subBtnLoading = false;
                this.$message.success(message);
                this.$emit('reload');
                this.closeDialog();
              })
              .catch((e) => {
                this.subBtnLoading = false;
                this.$message.error(e.toString());
              });
          } else {
            const message = '提交成功';
            this.subBtnLoading = true;
            this.$api.tjpt.budget
              .add(this.formData)
              .then((response) => {
                this.subBtnLoading = false;
                this.$message.success(message);
                this.$emit('reload');
                this.closeDialog();
              })
              .catch((e) => {
                this.subBtnLoading = false;
                this.$message.error(e.toString());
              });
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    closeDialog() {
      this.$emit('update:visible', false);
    },
  },
};
</script>
